package com.addzero.kmp.processor

import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.validate

private const val PKG = "com.addzero.kmp.service"
/**
 * 字符串首字母小写
 */
fun String.lowerFirst(): String {
    if (isEmpty()) return this
    return first().lowercase() + substring(1)
}

private const val str = """ServiceProvider"""

@Deprecated("生成在share共享模块,这个懒人库弃用")
class ServiceProviderProcessor(
    private val codeGenerator: CodeGenerator,
    private val logger: KSPLogger,
    private val options: Map<String, String>
) : SymbolProcessor {

    override fun process(resolver: Resolver): List<KSAnnotated> {
        val symbols = resolver.getSymbolsWithAnnotation("com.lt.lazy_people_http.annotations.LazyPeopleHttpService")
        val services = symbols.filterIsInstance<KSClassDeclaration>()
            .filter { it.validate() }
            .toList()

        if (services.isEmpty()) return emptyList()

        // 收集所有源文件的依赖
        val dependencies = services.map { it.containingFile!! }.toSet()


        val text = """
            package com.addzero.kmp.service

            import com.addzero.kmp.core.network.AddHttpClient.hfconfig
            import com.lt.lazy_people_http.annotations.LazyPeopleHttpService

            /**
             * 服务实例提供
             * 由KSP自动生成
             */
            object $str {
                ${
            services.joinToString("\n    ") { service ->
                val qfName = service.qualifiedName!!.asString()
                val simpleName = service.simpleName.asString().lowerFirst()
                "val $simpleName: $qfName = $qfName::class.createService(hfconfig)"
            }
        }
            }
        """.trimIndent()

        val file = codeGenerator.createNewFile(
            dependencies = Dependencies(true, *dependencies.toTypedArray()),
            packageName = PKG,
            fileName = str
        ).use { stream ->
            stream.write(text.toByteArray())
        }


        return emptyList()
    }
}

class ServiceProviderProcessorProvider : SymbolProcessorProvider {

    override fun create(
        environment: SymbolProcessorEnvironment
    ): SymbolProcessor {
        return ServiceProviderProcessor(
            environment.codeGenerator,
            environment.logger,
            environment.options
        )
    }
}
